<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议 https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------
namespace app\api\controller\system;

use app\common\controller\AdminController;
use think\captcha\facade\Captcha;
use think\facade\Env;
use app\admin\model\SystemConfig;
use think\facade\Db;
use app\admin\model\SystemUserRole;

/**
 * Class Login
 *
 * @package app\admin\controller
 */
class Auth extends AdminController
{

    /**
     * 用户信息
     *
     * @return mixed
     */
    public function user()
    {
        // TODO 通过来验证登录
        // Authorization: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJ1c2VybmFtZVwiOlwiYWRtaW5cIixcInRlbmFudElkXCI6MX0iLCJleHAiOjE2NTc0MzY5MjQsImlhdCI6MTY1NzM1MDUyNH0.JJrIyf4UoZ0IscKsTze5hHUn9Ua8hzsPio2Gi-K4N48
        $request = $this->request;
        $user_id = $request->_USER['user_id'];
        
        // $user_id = 2;
        // 权限
        
        $admin = Db::name("system_user")->where("user_id", $user_id)
            ->field("*,user_id userId")
            ->find();
        // var_dump($admin);
        // $user_id = 1;
        
        $menuWhere = " a.tenant_id = {$admin['tenant_id']}";
        
        $roles = SystemUserRole::where('user_id', $user_id)->find();
        
        if (! empty($roles)) {
            $menuWhere .= " AND a.role_id in ( select role_id from wjyk_system_user_role where user_id  = {$user_id})";
        }
        
        $menu = Db::name("system_role_menu")->alias("a")
            ->leftJoin("system_menu b", "a.menu_id=b.menu_id")
            ->field("b.*,
        b.menu_id menuId,
        b.parent_id parentId,
        b.menu_type menuType,
        b.sort_number sortNumber,
        b.tenant_id tenantId,
        b.update_time updateTime,
        b.create_time createTime,
        a.tenant_id tenantId
        ")
            ->where($menuWhere)
            ->order("sort_number", "desc")
            ->group("a.menu_id")
            ->select();
        
        // 如果不为oem代理
        $agency_user_id = null;
        
        if ($admin['tenant_id'] == 2) {
            $oem_user = Db::name("system_user")->alias("a")
                ->where("a.user_id", $user_id)
                ->field("a.*,a.user_id oem_id")
                ->find();
        } elseif ($admin['tenant_id'] == 3) {
            $oem_user = Db::name("system_user")->alias("a")
                ->leftJoin("system_user b", "a.agency_id=b.user_id")
                ->where("a.user_id", $user_id)
                ->field("a.*,b.user_id oem_id")
                ->find();
        }
        if (! empty($oem_user) && $oem_user['oem_id'] != null) {
            $agency_user_id = $oem_user['oem_id'];
        }
        $site_ico = "";
        $site_title = "";
        if (! empty($agency_user_id)) {
            // var_dump($oem_user_id);
            $config = agencyconfig($agency_user_id);
            if (! empty($config)) {
                $site_ico = $config['site_ico'];
                $site_title = $config['logo_title'];
            }
        }
        
        //
        
        $roles = Db::name("system_role")->alias("a")
            ->field("a.*,a.role_id roleId,a.role_name roleName,a.role_code roleCode,a.tenant_id tenantId,a.create_time createTime,a.update_time updateTime")
            ->where("a.role_id in (select role_id from wjyk_system_user_role where user_id = {$user_id})")
            ->select();
        
        $admin['accountNonExpired'] = true;
        $admin['accountNonLocked'] = true;
        
        $admin['authorities'] = $menu;
        $admin['roles'] = $roles;
        $admin['site_ico'] = $site_ico;
        $admin['site_title'] = $site_title;
        // // 去请求c5
        // $url = "http://c5.weijuyunke.com/api/softwareApi/pirate";
        // $host = $this->request->domain();
        // $data = array(
        // 'rjbs' => 'syb_dl',
        // 'yuming' => $host
        // );
        // wtw_request($url, $data);
        
        return msg($admin, 0, "登录成功");
    }

    /**
     * 更新密码
     * @NodeAnotation(title="添加")
     */
    public function password()
    {
        $request = $this->request;
        $uid = $request->_UID;
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $oldPassword = $post['oldPassword'];
                
                $password = $post['password'];
                $password2 = $post['password2'];
                
                if ($password != $password2) {
                    return msg([], 1, "新密码两次输入不一致!");
                }
                $user = Db::name("system_user")->where("user_id", $uid)->find();
                
                if (empty($user)) {
                    return msg([], 403, "用户不存在!");
                }
                
                $oldPassword2 = $user['password'];
                if (md5($oldPassword) != $oldPassword2) {
                    return msg([], 1, "旧密码输入错误!");
                }
                
                Db::name("system_user")->where("user_id", $uid)->update([
                    "password" => md5($password)
                ]);
                
                if ($request->_TENANTID == 3) {
                    Db::name("recycle_partner")->where("user_id", $uid)->update([
                        "password" => $password
                    ]);
                }
                
                return msg([], 0, "修改成功");
            } catch (\Exception $e) {
                return msg([], 1, "修改失败");
            }
        }
    }
}
